#! /usr/bin/env python
# -*- coding: UTF-8 -*-
import datetime
import inspect
from contextlib import contextmanager

__author__ = 'xcma'
import functools
from . import log

gloable_key = {}


def get_func_called():
    """
    获取当前方法被调用路径,从1开始，因为0是自己，不能被用作公共方法
    :return:
    """
    src = inspect.stack()
    info = []
    for i in range(1, len(src)):
        func_name = src[i][3]
        func_path = src[i][1]
        func_line = src[i][2]
        if not func_name.count('<') and not func_path.count('python2.7'):
            called_func_info = [func_name, func_line, func_path]
            info.append(called_func_info)
    return info[1]


def printFuncName(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        fname = get_func_called()
        log.info(f'-----start:{fname[0]}----')
        fres = func(*args, **kwargs)
        log.info(f'-----end:{fname[0]}------')
        return fres

    return wrapper


def setKey(**kwargs):
    global gloable_key
    gloable_key.update(kwargs)
    return gloable_key


def getKey(key):
    try:
        rkey = gloable_key[key]
    except:
        rkey = 'not found'

    return rkey


def getKeyDel(key):
    try:
        rkey = gloable_key.pop(key)
    except:
        rkey = 'not found'
    return rkey


def ppTodict(postman_param):
    """
    将入参转换为字典格式
    eg:
        start_time:2020-05-27 00
        title:创建活动
        img_url:mp-test/0c/5e/0c5e7005a346d8a626bd453f0bb0d09b.jpeg
        description:直播描
        sponsor:如果运气不行就试试勇气
        tags:22,33
        is_playback:
        is_portrait:
        cookie:996bd7d3a220bc9666b03615ef54bc5a
        notice:
    :param postman_param:
    :return:
    """
    r = {}
    dl = postman_param.replace(' ', '').split('\n')
    for i in dl:
        if i:
            d = i.split(':')
            if d[1].isdecimal():
                r[d[0]] = d[1]
            else:
                r[d[0]] = str(d[1])
    log.debug(f'解析得到的字典为：{r}')
    return r


def getNow(format="%Y-%m-%d"):
    """
    %Y-%m-%d %H:%M:%S
    yesterday = today - datetime.timedelta(days=1)
    tomorrow = today + datetime.timedelta(days=1)
    :param format:
    :return:
    """
    # 获得当前时间
    now = datetime.datetime.now()
    # 转换为指定的格式:
    otherStyleTime = now.strftime(format)
    return otherStyleTime


def getTdate(spaceDate=0, format="%Y-%m-%d"):
    """
    获取距离当前日期spaceDate天的日期
    :param spaceDate: 1，2 ，-1，-2
    :param format:
    :return:
    """
    now = datetime.datetime.now()
    fdate = now + datetime.timedelta(spaceDate)
    return fdate.strftime(format)


def getBase64(path):
    import base64
    with open(path, "rb") as f:  # 转为二进制格式
        base64_data = base64.b64encode(f.read())  # 使用base64进行加密
    # return f"data:image/jpeg;base64,{str(base64_data, 'utf-8')}"
    return str(base64_data, 'utf-8')
